package ls.ch02.demo;


import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import java.io.IOException;


/**
 * @author ls
 * @Date 创建时间:2022/4/6 10:39
 * 描述:
 */

public class Demo1 {
    public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException, TransformerException {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        //从 DOM 工厂获得 DOM 解析器
        DocumentBuilder db = dbf.newDocumentBuilder();
        //解析 XML 文档，得到一个 Document 对象，即 DOM 树
        Document doc = db.parse("F:\\idea\\S3-All\\frame\\src\\ls\\ch02\\demo\\Demo1.xml");
        //得到所有 Brand 节点列表信息
        NodeList brandList = doc.getElementsByTagName("Brand");
        //循环 Brand 信息
        for (int i = 0; i < brandList.getLength(); i ++) {
            //获取第 i 个 Brand 元素信息
            Node brand = brandList.item(i);
            //获取第 i 个 Brand 元素的 name 属性的值
            Element element = (Element) brand;
            String attrValue = element.getAttribute("name");
            //获取第 i 个 Brand 元素的所有子元素的 name 属性值
            NodeList types = element.getChildNodes();
            for (int j = 0; j < types.getLength(); j ++) {
                Element typeElement = (Element) types.item(j);              //Type 节点
                String type = typeElement.getAttribute("name");       //获得手机型号
                System.out.println("手机:" + attrValue + type);
            }
        }
    }
}
